package com.yanyu.space.common.log.support;

import com.yanyu.space.common.log.handler.LogFactory;
import com.yanyu.space.common.log.handler.LogWorkerContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.core.Ordered;

/**
 * @author yanyu
 */
@Aspect
@Slf4j
public class LogAsyncAspect implements Ordered {

    private Tracer tracer;

    public LogAsyncAspect(Tracer tracer) {
        this.tracer = tracer;
    }

    @Around("execution (@org.springframework.scheduling.annotation.Async  * *.*(..))")
    public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable {
        this.tracer.currentSpan().event("cs");
        try (LogWorkerContext logWorkerContext = LogFactory.getInstance().start(this.tracer.currentSpan().context())) {
            return proceed(pjp);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    private Object proceed(final ProceedingJoinPoint pjp) {
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            log.error("{}", e.getMessage(), e);
        }
        return result;
    }
}
